<template>
  <div class="annotation-container">
    <div class="tool-header">
      <h3>图片标注工具</h3>
      <div class="tool-buttons">
        <el-button @click="resetCanvas" size="small">重置</el-button>
        <el-button @click="deleteSelected" size="small" :disabled="!selectedRect">删除选中</el-button>
        <el-button @click="saveAnnotatedImage" type="primary" size="small">保存标注图片</el-button>
      </div>
    </div>

    <div class="image-uploader">
      <el-upload
        action="#"
        :auto-upload="false"
        :show-file-list="false"
        :on-change="handleImageUpload"
        accept="image/*"
      >
        <el-button size="small">选择图片</el-button>
      </el-upload>
    </div>

    <div class="canvas-container" v-if="imageLoaded">
      <canvas
        ref="canvas"
        @mousedown="startDrawing"
        @mousemove="draw"
        @mouseup="stopDrawing"
        @mouseleave="stopDrawing"
      ></canvas>

      <div class="annotation-list" v-if="rectangles.length > 0">
        <h4>标注列表</h4>
        <div
          v-for="(rect, index) in rectangles"
          :key="index"
          class="rect-item"
          :class="{ selected: selectedIndex === index }"
          @click="selectRect(index)"
        >
          标注 {{ index + 1 }}: ({{ rect.x }}, {{ rect.y }}) - 宽:{{ rect.width }}, 高:{{ rect.height }}
        </div>
      </div>
    </div>

    <div class="status-bar" v-if="imageLoaded">
      {{ statusMessage }}
    </div>
  </div>
</template>

<script>
export default {
  name: "ImageAnnotationTool",
  data() {
    return {
      image: null,
      canvas: null,
      ctx: null,
      imageLoaded: false,
      drawing: false,
      startX: 0,
      startY: 0,
      currentX: 0,
      currentY: 0,
      rectangles: [],
      selectedIndex: -1,
      statusMessage: "请选择图片并开始标注"
    };
  },
  computed: {
    selectedRect() {
      return this.selectedIndex >= 0 ? this.rectangles[this.selectedIndex] : null;
    }
  },
  methods: {
    handleImageUpload(file) {
      const reader = new FileReader();
      reader.onload = (e) => {
        this.image = new Image();
        this.image.onload = () => {
          this.imageLoaded = true;
          this.$nextTick(() => {
            this.initCanvas();
          });
        };
        this.image.src = e.target.result;
      };
      reader.readAsDataURL(file.raw);
    },

    initCanvas() {
      this.canvas = this.$refs.canvas;
      this.ctx = this.canvas.getContext('2d');

      // 设置canvas尺寸与图片相同
      this.canvas.width = this.image.width;
      this.canvas.height = this.image.height;

      // 绘制图片
      this.redrawImage();
      this.statusMessage = "图片已加载，拖动鼠标绘制标注框";
    },

    startDrawing(e) {
      if (!this.imageLoaded) return;

      const rect = this.canvas.getBoundingClientRect();
      this.startX = e.clientX - rect.left;
      this.startY = e.clientY - rect.top;
      this.drawing = true;

      // 清除选中状态
      this.selectedIndex = -1;
    },

    draw(e) {
      if (!this.drawing) return;

      const rect = this.canvas.getBoundingClientRect();
      this.currentX = e.clientX - rect.left;
      this.currentY = e.clientY - rect.top;

      this.redrawImageWithTempRectangle();
    },

    stopDrawing() {
      if (!this.drawing) return;
      this.drawing = false;

      // 计算矩形坐标和尺寸
      const x = Math.min(this.startX, this.currentX);
      const y = Math.min(this.startY, this.currentY);
      const width = Math.abs(this.currentX - this.startX);
      const height = Math.abs(this.currentY - this.startY);

      if (width > 5 && height > 5) { // 忽略太小的矩形
        this.rectangles.push({ x, y, width, height });

        // 更新状态信息
        const centerX = x + width / 2;
        const centerY = y + height / 2;
        this.statusMessage = `标注已添加 - 中心坐标: (${Math.round(centerX)}, ${Math.round(centerY)}), 宽度: ${width}, 高度: ${height}`;

        this.redrawImage();
      }
    },

    redrawImage() {
      this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height);
      this.ctx.drawImage(this.image, 0, 0);

      // 绘制所有矩形
      this.ctx.strokeStyle = 'red';
      this.ctx.lineWidth = 2;

      this.rectangles.forEach((rect, index) => {
        this.ctx.strokeRect(rect.x, rect.y, rect.width, rect.height);

        // 如果是选中的矩形，绘制不同颜色
        if (index === this.selectedIndex) {
          this.ctx.strokeStyle = 'blue';
          this.ctx.strokeRect(rect.x, rect.y, rect.width, rect.height);
          this.ctx.strokeStyle = 'red';
        }
      });
    },

    redrawImageWithTempRectangle() {
      this.redrawImage();

      // 绘制当前正在拖动的矩形
      if (this.drawing) {
        const x = Math.min(this.startX, this.currentX);
        const y = Math.min(this.startY, this.currentY);
        const width = Math.abs(this.currentX - this.startX);
        const height = Math.abs(this.currentY - this.startY);

        this.ctx.strokeStyle = 'green';
        this.ctx.lineWidth = 2;
        this.ctx.strokeRect(x, y, width, height);
      }
    },

    selectRect(index) {
      this.selectedIndex = index;
      this.redrawImage();

      const rect = this.rectangles[index];
      const centerX = rect.x + rect.width / 2;
      const centerY = rect.y + rect.height / 2;
      this.statusMessage = `选中标注 ${index + 1} - 中心坐标: (${Math.round(centerX)}, ${Math.round(centerY)}), 宽度: ${rect.width}, 高度: ${rect.height}`;
    },

    deleteSelected() {
      if (this.selectedIndex >= 0) {
        this.rectangles.splice(this.selectedIndex, 1);
        this.selectedIndex = -1;
        this.redrawImage();
        this.statusMessage = "已删除选中标注";
      }
    },

    resetCanvas() {
      this.rectangles = [];
      this.selectedIndex = -1;
      this.redrawImage();
      this.statusMessage = "已重置所有标注";
    },

    // 修改后的保存方法 - 直接保存标注后的图片
    saveAnnotatedImage() {
      if (!this.imageLoaded) {
        this.$message.warning("请先上传图片");
        return;
      }

      // 创建一个临时链接用于下载
      const dataURL = this.canvas.toDataURL('image/jpeg');
      const link = document.createElement('a');

      // 获取当前时间作为文件名的一部分
      const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
      const fileName = `annotated-image-${timestamp}.jpg`;

      link.href = dataURL;
      link.download = fileName;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);

      this.$message.success("标注图片已保存");

      // 如果需要直接上传到服务器而不是下载，可以使用以下代码：
      /*
      this.canvas.toBlob((blob) => {
        const formData = new FormData();
        formData.append('annotatedImage', blob, 'annotated-image.jpg');
        formData.append('diseaseName', this.diseaseName);
        formData.append('symptoms', this.symptoms);
        formData.append('solution', this.solution);

        this.$axios.post('/api/disease/annotate-image', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(response => {
          this.$message.success("标注图片已上传到服务器");
        }).catch(error => {
          this.$message.error("上传失败");
        });
      }, 'image/jpeg', 0.9);
      */
    }
  }
};
</script>

<style scoped>
.annotation-container {
  padding: 20px;
  border: 1px solid #eaeaea;
  border-radius: 4px;
  margin-bottom: 20px;
}

.tool-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.canvas-container {
  display: flex;
  margin-top: 15px;
}

canvas {
  border: 1px solid #ddd;
  max-width: 100%;
  height: auto;
  cursor: crosshair;
}

.annotation-list {
  margin-left: 20px;
  min-width: 250px;
}

.rect-item {
  padding: 8px;
  margin-bottom: 5px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}

.rect-item:hover {
  background-color: #f5f5f5;
}

.rect-item.selected {
  background-color: #e6f7ff;
  border-color: #91d5ff;
}

.status-bar {
  margin-top: 10px;
  padding: 8px;
  background-color: #f9f9f9;
  border-radius: 4px;
  font-size: 14px;
}

.image-uploader {
  margin-bottom: 15px;
}
</style>

